package net.yihang.miaosha.controller;

import net.yihang.miaosha.controller.result.CodeMsg;
import net.yihang.miaosha.domain.MiaoshaUser;
import net.yihang.miaosha.domain.MiaoshaUserKey;
import net.yihang.miaosha.service.AfterLoginSuccess;
import net.yihang.miaosha.service.LoginService;
import net.yihang.miaosha.service.RedisService;
import net.yihang.miaosha.util.CookieUtil;
import net.yihang.miaosha.vo.MiaoshaUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Controller()
@RequestMapping("/login")
public class LoginController {
    public static final String LOGIN_TOKEN_NAME = "login_token";

    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisService redisService;

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/doLogin")
    @ResponseBody
    public ResponseEntity<CodeMsg> doLogin(@Valid MiaoshaUserVO userVO, HttpServletResponse response) {

        long mobile = Long.valueOf(userVO.getMobile());
        String password = userVO.getPassword();
        CodeMsg codeMsg = loginService.login(mobile, password, new AfterLoginSuccess() {
            @Override
            public void execute(MiaoshaUserKey key, MiaoshaUser user) {
                redisService.set(key, user);
                CookieUtil.updateTokenCookie(response, key);
            }
        });
        if (codeMsg == CodeMsg.LOGIN_SUCCESS) {
            return ResponseEntity.ok(codeMsg);
        } else {
            return ResponseEntity.badRequest().body(codeMsg);
        }
    }

}
